<?php
require_once('TVB/SSH/SSHAgent.php');
require_once('LUCException.class.php');

class LuceneXml
{
	private $host;
	private $port;
	private $user;
	private $passpharse;
	private $public_key_file;
	private $private_key_file;
    private $_lucene_xml_push_path;
    private $_xml_catche_path;
    private $_xml;
    private $_xmls_to_lucene = array(
        'programme' => array(),
        'episode' => array(),
        'cast' => array(),
        'video' => array(),
        'chapter' => array(),
        'info' => array(),
        'image' => array(),
        'folder' => array(),
        'folder_video' => array(),
        'folder_image' => array(),
    );

    public function __construct()
    {
        $this->_xml_catche_path = AC::LUCENE_XML_PATH_PC1;
        $this->_lucene_xml_push_path = AC::LUCENE_XML_PATH_PC2;

		$config = ConfigReaderFactory::getInstance()->getConfigReader(AC::LUCENE_CONFIG_FILE)->getConfig();
		$ssh = $config->ssh;
		$this->host = (string) $ssh->host;
		$this->port = intval($ssh->port);
		$this->user = (string) $ssh->user;
		$this->passpharse = (string) $ssh->passpharse;
		$this->public_key_file = (string) $ssh->public_key;
		$this->private_key_file = (string) $ssh->private_key;
    }

    public function newLuceneXml($type, $data, $act='add')
    {
        if (!is_array($data) || empty($data)) {
            throw new LUCException("Create lucene xml failure, input data is empty.");
        }

        $this->_xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
		$this->_xml .= "<!-- from portal consumer -->\n" ;
        switch ($act) {
        case 'add':
            $this->_xml .= "<add>\n";
            $this->_xmlForAddEdit($data);
            $this->_xml .= "</add>\n";
            break;
        case 'edit':
            $this->_xml .= "<add>\n";
            $this->_xmlForAddEdit($data);
            $this->_xml .= "</add>\n";
            break;
        case 'del':
            $this->_xml .= "<delete>\n";
            $this->_xmlForDelete($data);
            $this->_xml .= "</delete>\n";
            break;
        default:
           throw new LUCException("Create lucene xml failure, No {$act} option, add/edit/del for your reference."); 
        }

        $file = $this->_path($type, $act);
        file_put_contents($file, print_r($this->_xml, 1));
        if (is_readable($file)) {
            return $file;
        } else {
            throw new LUCException("Create lucene xml({$file}) failure.");
        }
    }

    public function addXmlNeedPush($type, $file)
    {
        $this->_xmls_to_lucene[$type][] = $file; 
    }

    public function pushXmlToLuceneServer()
    {
		$ssh = new SSHAgent($this->host, $this->port, $this->user, $this->public_key_file, $this->private_key_file, $this->passpharse);

        foreach ($this->_xmls_to_lucene as $type=>$files) {
            foreach ($files as $key=>$local_file) {
                if (file_exists($local_file)) {
                    $remote_file = $this->_lucene_xml_push_path."/".$this->destinationFolder($type)."/".basename($local_file) ;
					error_log ( "[".date('Y-m-d H:i:s')."] scp ${local_file} to {$remote_file}" ) ;
			        $ret = $ssh->sendFile($local_file, $remote_file);
                    if ($ret === FALSE) {
                        throw new LUCException("Send xml({$local_file}) to lucene Server failure.");
                    } else {
                        unset($this->_xmls_to_lucene[$type][$key]);
                    }
                } else {
                    throw new LUCException("Lucene xml({$local_file}) not found.");
                }
            }
        } 
    }

    public function destinationFolder($type)
    {
        $folder = array(
            'programme' => 'Programme',
            'episode' => 'Episode',
            'cast' => 'Cast',
            'video' => 'Video',
            'chapter' => 'Chapter',
            'info' => 'Info',
            'image' => 'Image',
            'folder' => 'Folder',
            'folder_video' => 'FolderVideo',
            'folder_image' => 'FolderImage',
            'p_programme' => 'Programme',
            'p_episode' => 'Episode',
            'p_cast' => 'Cast',
            'p_video' => 'Video',
            'p_chapter' => 'Chapter',
            'p_info' => 'Info',
            'p_image' => 'Image',
            'p_folder' => 'Folder',
            'p_folder_video' => 'FolderVideo',
            'p_folder_image' => 'FolderImage',

        );
        return $folder[$type];
    }

    private function _path($type, $act)
    {
        $path = $this->_xml_catche_path.'/'.$type;
        if (is_dir($path)) {
		//$fileName = rand(1,50000);
		$fileName = "{$type}{$act}".date("YmdHis");
		$fileName = md5($fileName);
            return $this->_xml_catche_path.'/'.$type.'/'.$act.'_'.$fileName.'.xml';
        } else {
            throw new LUCException("Create lucene xml failure: PATH({$path}) not found.");
        }
    }

    private function _xmlForAddEdit($data)
    {
        foreach ($data as $row) {
            if (isset($row['uri'])) {
                unset($row['uri']);
            }

            $this->_xml .= "\t<doc>\n";
            foreach ($row as $key=>$value) {
                if (preg_match("/[<|>|\"|'|&]/", $value)) {
                    $this->_xml .= "\t\t<field name=\"{$key}\"><![CDATA[{$value}]]></field>\n";
                } else {
                    $this->_xml .= "\t\t<field name=\"{$key}\">{$value}</field>\n";
                }
            }
            $this->_xml .= "\t</doc>\n";
        }
    }

    private function _xmlForDelete($data)
    {
        foreach ($data as $row) {
            $this->_xml .= "\t\t<query>id:".$row['id']."</query>\n";
        }
    }
}
?>
